import BasePanel from "../BasePanel";
import saveItem from "./saveItem";

const {ccclass, property} = cc._decorator;

@ccclass
export default class SavePanel extends BasePanel {
    @property(cc.Prefab)
    saveItemPrefab:cc.Prefab=null;
    private saveItemParent:cc.Node;
    private layout:cc.Layout;
    private widget:cc.Widget;
    onLoad(){
        this.close;
        this.saveItemParent = this.node.getChildByName("scrollview").getChildByName("view").getChildByName("content");
        this.layout = this.saveItemParent.getComponent(cc.Layout);
        this.widget = this.saveItemParent.getComponent(cc.Widget);

        /** 新增了一个保存数据位 */
        this.node.on("SaveOrLoad",this.Save,this);
    }

    firstCall(){    
        if(!this.isFirst) return;        
        this.isFirst = false;
        //初始化存档

        var saveAll = cc.sys.localStorage.getItem("save");        
        if(saveAll){
            saveAll = JSON.parse(saveAll);
            saveAll.forEach( (item,key)=>{
                var node = this.saveItemParent.children[key];
                if(!node){
                    node = cc.instantiate(this.saveItemPrefab);   
                    node.parent = this.saveItemParent;             
                }            
                var com = node.getComponent(saveItem);            
                com.saveItem = item;
            })
        }
        this.AddSaveItem();
    }    

    AddSaveItem(){
        var node = cc.instantiate(this.saveItemPrefab);
        node.parent = this.saveItemParent;
        this.layout.updateLayout();
        this.widget.updateAlignment();
    }

    /** 保存一个记录 */
    Save(event:cc.Event.EventCustom){
        var node:cc.Node = event.target;
        var index = node.getSiblingIndex();

        var game = QM.game.toObj();
        var saveAll = cc.sys.localStorage.getItem("save");
        if(saveAll){
            saveAll = JSON.parse(saveAll);
        }else{
            saveAll = [];
        }      
        saveAll[index] = game
        cc.sys.localStorage.setItem("save",JSON.stringify(saveAll));
        node.getComponent(saveItem).saveItem = game;
      
        if(index+1>=this.saveItemParent.childrenCount){
            this.AddSaveItem();
        }

    }
}
